<!--
 * @Description:
 * @Author:
 * @Date: 2024-11-01 00:09:29
 * @LastEditTime: 2025-02-16 10:47:01
 * @LastEditors: XXX
-->
<template>
  <div class="login-container">

    <video
      poster="../../../assets/images/login/video-cover.jpeg"
      loop
      autoplay
      muted
    >
      <source src="~@/assets/images/login/night.mp4">
    </video>

    <el-form
      ref="loginFormRef"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left">
      <div class="title-container">
        <h3 class="title">
          {{ t('login.title') }}
        </h3>
        <SelectLang :isWhite="true" class="set-language"/>
      </div>

      <el-form-item prop="username">
        <el-icon class="svg-container">
          <User></User>
        </el-icon>
        <el-input ref="userNameRef"
          v-model.trim="loginForm.username"
          :placeholder="t('login.username')"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>

      <el-tooltip v-model:visible="capsTooltip"
        content="Caps lock is On"
        placement="right"
        manual>
        <el-form-item prop="password">
          <el-icon class="svg-container">
            <Lock></Lock>
          </el-icon>
          <el-input
            v-model.trim="loginForm.password"
            :key="passwordType"
            ref="passwordRef"
            :type="passwordType"
            :placeholder="t('login.password')"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup="checkCapsLock"
            @blur="capsTooltip = false"
            @keyup.enter="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :name="passwordType === 'password' ? 'iconEye' : 'icon-eye-close'" color="#ffffff"></svg-icon>
          </span>
        </el-form-item>
      </el-tooltip>

      <el-button class="mb15" style="width: 100%;" :loading="loading" type="primary" @click.prevent="handleLogin">
        {{ t("login.logIn") }}
      </el-button>

      <div class="login-button-wrapper">
        <el-button class="thirdparty-button mb15" type="primary" @click="openShowDialog">
          {{ t('login.thirdparty') }}
        </el-button>

        <div class="tips">
          <span>{{ t("login.username") }} : admin/editor </span>
          <span>{{ t("login.password") }} : {{ t("login.any") }} </span>
        </div>
      </div>
    </el-form>

    <el-dialog :title="t('login.thirdparty')" v-model="showDialog">
      {{ t("login.thirdpartyTips") }}
      <br>
      <br>
      <br>
      <SocialSignin></SocialSignin>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import SocialSignin from './components/SocialSignin.vue';
import SelectLang from '@/components/lang_select/index.vue'
import { useStore } from '@/store'
import { useI18n } from 'vue-i18n';
import { reactive, ref, onMounted, watch, nextTick } from 'vue';
import { UserActionTypes } from '@/store/modules/user/action-types';
import { useRouter, useRoute, type LocationQuery } from 'vue-router'
import { isValidateUserName } from '@/utils/validate'

const { t } = useI18n()

const passwordType = ref('password')
const showDialog = ref(false)
const loading = ref(false)
const loginFormRef = ref()
const userNameRef = ref<HTMLInputElement | null>(null)
const passwordRef = ref<HTMLInputElement | null>()
const redirect = ref('')
const otherQuery = ref({})
const store = useStore()
const router = useRouter()
const route = useRoute()
const capsTooltip = ref(false)

const loginForm = reactive({
  username: 'admin',
  password: '111111'
})

const loginRules = reactive({
  username: [{ validator: validateUserName, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }]
})

function validateUserName (rule:any, value:string, callback:Function) {
  if (!value) {
    callback(new Error('Please enter user name'))
  } else if (!isValidateUserName(value)) {
    callback(new Error('Please enter the correct user name'))
  } else {
    callback()
  }
}

function validatePassword (rule:any, value:string, callback:Function) {
  if (!value) {
    callback(new Error('Please enter password.'))
  } else if (value.length < 6) {
    callback(new Error('The password can not be less than 6 digits.'))
  } else {
    callback()
  }
}

const showPwd = () => {
  console.log('showPwd')
  if (passwordType.value === 'password') {
    passwordType.value = ''
  } else {
    passwordType.value = 'password'
  }
  nextTick(() => {
    passwordRef.value?.focus()
  })
}

// NOTE:实现方案错误
const checkCapsLock = (e: KeyboardEvent) => {
  // getModifierState存在兼容性问题
  const { key/*, getModifierState*/ } = e
  console.log('key :>> ', key);
  // const state = getModifierState('CapsLock')
  // console.log('state :>> ', state);
  capsTooltip.value = key !== null && key.length === 1 && key >= 'A' && key <= 'Z'
}

const openShowDialog = () => {
  showDialog.value = true
}

const handleLogin = () => {
  console.log('loginFormRef.value :>> ', loginFormRef.value);
  loginFormRef.value.validate(async (valid:boolean, ...args:any[]) => {
    if (valid) {
      loading.value = true
      await store.dispatch(UserActionTypes.ACTION_LOGIN, loginForm)
      router.push({
        path: redirect.value || '/',
        query: otherQuery.value
      })
      setTimeout(() => {
        loading.value = false
      }, 500)
    }
  })
}

const getOtherQuery = (query: LocationQuery) => {
  return Object.keys(query).reduce((acc, cur) => {
    if (cur !== 'redirect') {
      acc[cur] = query[cur]
    }
    return acc
  }, {} as LocationQuery)
}

watch(() => route.query, query => {
  console.log('watch query :>> ', query);
  if (query) {
    redirect.value = query.redirect?.toString() ?? ""
    otherQuery.value = getOtherQuery(query)
  }
}, {
  immediate: true
})

onMounted(() => {
  if (loginForm.username === '') {
    userNameRef.value?.focus()
  } else {
    passwordRef.value?.focus()
  }
})
</script>

<style lang="scss" scoped>
.login-container {
  width: 100%;
  height: 100%;
  overflow: hidden;

  video {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    z-index: -1;
  }

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;

    .login-button-wrapper {
      .tips {
        font-size: 14px;
        color: #fff;
        margin-bottom: 10px;
        opacity: 0.5;

        span {
          &:first-of-type {
            margin-right: 16px;
          }
        }
      }

      .thirdparty-button {
        width: 100%;
      }
    }
  }

  .title-container {
    position: relative;

    .title {
      font-style: 26px;
      color: $lightGray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }

    .set-language {
      color: #fff;
      position: absolute;
      top: 15px;
      font-size: 18px;
      right: -10px;
      cursor: pointer;
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;

    .svg-container {
      padding: 2px 5px 6px 15px;
      color: $lightGray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
      font-size: 16px;
    }

    .el-input {
      display: inline-block;
      height: 47px;
      width: calc(100% - 60px);

      :deep(input),
      :deep(.el-input__wrapper) {
        width: 100%;
        height: 47px;
        background: transparent !important;
        border: 0px;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $lightGray;
        caret-color: $loginCursorColor;
        border: 0;
        outline: none;
        box-shadow: none;

        // &::autofill,
        // &::-webkit-autofill {
        //   background-color: transparent;
        // }
      }
    }
  }
}
</style>
